/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.dao;

import br.com.dao.util.GenericDao;
import br.com.model.Cliente;
import br.com.model.Item;
import br.com.model.Reserva;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import br.com.type.CodigoBarras;
import br.com.type.EstadoItem;
import br.com.model.TipoMidia;
import br.com.model.Filme;
import br.com.servlets.CadastroItem;
import java.util.logging.Level;
import java.util.logging.Logger;
import br.com.type.CodigoBarras;
import br.com.type.EstadoReserva;
import java.util.Collection;
import javax.xml.bind.ParseConversionEvent;





/**
 *
 * @author Hercules Sandim
 */
public class ReservaDao implements GenericDao<Reserva> 
    {

    private Connection connection;

    public ReservaDao(Connection connection) {
        this.connection = connection;
    }
    
    @Override
     public void save(Reserva reserva) {
        PreparedStatement stmt = null;
        try
        {
         this.connection.setAutoCommit(false);   
            String sql;
          
  
            
            //PreparedStatement stmt = this.connection.prepareStatemen
            sql="insert into reserva " +
                    " (datareserva, datacomunicacao,estado,cliente) "+
                    " values (?,?,?,?)"  ;
            stmt = this.connection.prepareStatement(sql);
            stmt.setDate(1, reserva.getDtReserva());
            stmt.setDate(2, reserva.getDtComunicacaoCliente());
            stmt.setString(3, reserva.getEstado().toString());            
            stmt.setString(4, reserva.getCliente().getNumeroInscricao());
            stmt.executeUpdate();
            this.connection.commit();
            
            Integer id;
            sql = "select max(id) as id from reserva"; //Funciona para PostgreSQL
            stmt = this.connection.prepareStatement(sql);
            ResultSet rs = stmt.executeQuery();
            rs.next();
            id = rs.getInt(1);
            System.out.println(id);

            
            sql="insert into reserva_item "+
                   "(id_reserva, itemreservado) "+
                   " values (?,?) ";
            stmt = this.connection.prepareStatement(sql);
            for(int i = 0; i < reserva.getItemsReservados().toArray().length; i++){     
                stmt.setInt(1, id);
                stmt.setString(2, reserva.getItemsReservados().get(i).getNumeroSerie().getCodigoBarras());
                stmt.executeUpdate();
                this.connection.commit();
            }
    
        } catch (SQLException e) {
            e.printStackTrace();
            if(this.connection != null){
                try{
                    System.err.print("Transaction is beign rolled back");
                    this.connection.rollback();
                }catch(SQLException excep){
                    System.err.println(excep);
                }
            }
        }
        finally{
               if(stmt != null){
                   try{
                       stmt.close();
                   }catch(SQLException ex){
                       Logger.getLogger(LocacaoDao.class.getName()).log(Level.SEVERE, null, ex);
                   }
               }
                try {
                    this.connection.setAutoCommit(true);
                } catch (SQLException ex) {
                    Logger.getLogger(LocacaoDao.class.getName()).log(Level.SEVERE, null, ex);
                }
        }
    }
    
    @Override
    public void delete(Reserva reserva) {
       try
        { 
            String id, sql;
            id = reserva.getIdReserva().toString();
            sql="delete from reserva where id =  "+id;
            PreparedStatement stmt = this.connection.prepareStatement(sql); 
            stmt.executeUpdate();
        }    
        catch (SQLException e)
        {
                e.printStackTrace();
        }
        
        //throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public Collection<Reserva> list() {
        LinkedList<Reserva> listareserva = null;
        Reserva reserva = null;
        LinkedList<Item> lista = new LinkedList<Item>();      
        Item item = null;
        Cliente cliente = null;
        int id;
        try{
            String sql = "select * from reserva";
            PreparedStatement stmt = this.connection.prepareStatement(sql); 
            ResultSet rs = stmt.executeQuery();
            id = rs.getInt(1);
            while(rs.next()){
                String sql2 = "select itemreservado from item_reserva where id_reserva = "+id;
                PreparedStatement stmt2 = this.connection.prepareStatement(sql2); 
                ResultSet rs2 = stmt2.executeQuery();
                while(rs2.next()){
                       CodigoBarras codigo = null; 
                    try {
                        codigo = new CodigoBarras(rs.getString(1));
                    } catch (Exception ex) {
                        Logger.getLogger(CadastroItem.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    item = new Item(codigo);
                    lista.add(item);
                }
                cliente = new Cliente(rs.getString(4));
                if(rs.next()){   
                    reserva  = new Reserva( rs.getInt(1), rs.getDate(2), rs.getDate(3), EstadoReserva.valueOf(rs.getString(4)), lista, cliente );     
                }
                listareserva.add(reserva);
            }
            
        }   
        catch (SQLException e){
            e.printStackTrace();
        }
        return listareserva;
    }

    @Override
    public Reserva findById(Integer id) {
         Reserva reserva = null;
         LinkedList<Item> list = new LinkedList<Item>();      
         Item item = null;
         Cliente cliente = null;
        try{
            String sql = "select * from reserva where id= "+id;
            PreparedStatement stmt = this.connection.prepareStatement(sql); 
            ResultSet rs = stmt.executeQuery();
            String sql2 = "select itemreservado from item_reserva where id_reserva = "+id;
            PreparedStatement stmt2 = this.connection.prepareStatement(sql2); 
            ResultSet rs2 = stmt2.executeQuery();
            while(rs2.next()){
                   CodigoBarras codigo = null; 
                try {
                    codigo = new CodigoBarras(rs.getString(1));
                } catch (Exception ex) {
                    Logger.getLogger(CadastroItem.class.getName()).log(Level.SEVERE, null, ex);
                }
                item = new Item(codigo);
                list.add(item);
            }
            cliente = new Cliente(rs.getString(4));
            if(rs.next()){   
                reserva  = new Reserva( rs.getInt(1), rs.getDate(2), rs.getDate(3), EstadoReserva.valueOf(rs.getString(4)), list, cliente );     
            }
        }
        catch (SQLException e){
            e.printStackTrace();
        }
        return reserva;
        //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public LinkedList<Reserva> listar() {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public Reserva getObjectById(Integer id) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public LinkedList<Reserva> getObjectByName(String name) {
        throw new UnsupportedOperationException("Not supported yet.");
    }
    
}